<?php 
/**
 * order.php
 *
 * Orders management
 *
 * @author     Makai Lajos
 * @copyright  2015
 * @license    License.txt
 * @version    2.0
 * @link       http://opencart-api.com/product/opencart-restful-api-pro-v2-0/
 * @see        http://newapi2.opencart-api.com/demo/
 */
require_once(DIR_SYSTEM . 'engine/restcontroller.php');

class ControllerRestOrder extends RestController {
	
	private $error = array();

	public function getProductByOrder($order_id){
		if ( $order_id ){
			$this->load->model('catalog/product');
			$results=$this->model_catalog_product->getProductsByOrder($order_id);

			return $results;
		}
		else{
			return 0;
		}
		
	}

	public function listOrders() {
		$json = array('success' => true);
		
		if (!$this->customer->isLogged()) {
			$json["error"]['warning'] = "用户未登录";
			$json["success"] = false;
		}

		$this->language->load('account/order');

		$this->load->model('account/order');

		if($json["success"]){
			$page = 1;

			$data['orders'] = array();

			$order_total = $this->model_account_order->getTotalOrders();

			$results = $this->model_account_order->getOrders(($page - 1) * 10, 1000);

			foreach ($results as $result) {
				$product_total = $this->model_account_order->getTotalOrderProductsByOrderId($result['order_id']);
				$voucher_total = $this->model_account_order->getTotalOrderVouchersByOrderId($result['order_id']);

				//判断本订单的幸运抽奖情况
				$luckydraw = $this->model_account_order->getLuckydraw($result);
				$is_pay	 = $result['is_pay']?'(已付款)':'(未付款)';
				$pata = array(
					'order_id'   => $result['order_id'],
					'pay_id' =>$result['order_id'].$result['id_code'],
					'name'       => $result['fullname'] ,
					'status'     => $result['status'].$is_pay,
					'order_status_id'     => $result['order_status_id'],
					'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added'])),
					'products'   => ($product_total + $voucher_total),
					'total'      => $this->currency->format($result['total'], $result['currency_code'], $result['currency_value']),
                    'currency_code'	=> $result['currency_code'],
                    'currency_value'=> $result['currency_value'],
                    'product_detail'=> $this->getProductByOrder($result['order_id']),
					'payment_code'=> $result['payment_code'],
					'payment_method' => $result['payment_method'],
                    'luckydraw'=>$luckydraw
				);
				if($result['is_pay'] == 0){
					$pata['need_pay'] = 1;
				}else{
					$pata['need_pay'] = 0;
				}

				if($result['status'] != "无效") {
					$data2['全部'][] = $pata;
				}

				if($result['status'] == '部分发货' || $result['status'] == "全部发货" || $result['status'] == "待收货") {
					$data2['待收货'][] = $pata;
				}
				elseif($result['is_pay'] == 0 && $result['status'] != "无效"){
					$data2['待付款'][] = $pata;
				}
				elseif($result['status'] == '待发货' || $result['status'] == '待审核'){
					$data2['待发货'][] = $pata;
				}else{
					$data2[$result['status']][] = $pata;
				}

			}

			$data['orders']=$data2;
			if(count($data['orders']) > 0){
				$json["data"] = $data;
			}else {
				$json["data"] = $data;
				// $json["success"] = false;
				// $json["error"]['warning']= "没有找到用户订单";
			}
		}

		if ($this->debugIt) {
			echo '<pre>';
			print_r($json);
			echo '</pre>';
		} else {
			$this->response->setOutput(json_encode($json));
		}					
	}

	public function getOrder($order_id) { 
		
		$json = array('success' => true);

		$this->language->load('account/order');


		if (!$this->customer->isLogged()) {
			$json["error"]['warning']= "用户没有登陆";
			$json["success"] = false;
		}
		
		if($json["success"]){
			$this->load->model('account/order');

			$order_info = $this->model_account_order->getOrder($order_id);

			if ($order_info) {
                $data = $order_info;
				if ($order_info['invoice_no']) {
					$data['invoice_no'] = $order_info['invoice_prefix'] . $order_info['invoice_no'];
				} else {
					$data['invoice_no'] = '';
				}

				$data['order_id'] = $order_id;
				$data['date_added'] = date($this->language->get('date_format_short'), strtotime($order_info['date_added']));

				if ($order_info['payment_address_format']) {
					$format = $order_info['payment_address_format'];
				} else {
					$format = '{fullname} ' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
				}

				$find = array(
					'{fullname}',
					'{company}',
					'{address_1}',
					'{address_2}',
					'{city}',
					'{postcode}',
					'{zone}',
					'{zone_code}',
					'{country}'
				);

				$replace = array(
					'fullname'  => $order_info['payment_fullname'],
					'company'   => $order_info['payment_company'],
					'address_1' => $order_info['payment_address_1'],
					'address_2' => $order_info['payment_address_2'],
					'city'      => $order_info['payment_city'],
					'postcode'  => $order_info['payment_postcode'],
					'zone'      => $order_info['payment_zone'],
					'zone_code' => $order_info['payment_zone_code'],
					'country'   => $order_info['payment_country']
				);

				// $data['payment_address'] = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));
				$data['payment_address'] = $order_info['payment_address'];
				$is_pay = $order_info['is_pay']?'(已付款)':'(未付款)';

				$data['payment_method'] = $order_info['payment_method'].$is_pay;

				if ($order_info['shipping_address_format']) {
					$format = $order_info['shipping_address_format'];
				} else {
					$format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
				}

				$find = array(
					'{fullname}',
					'{company}',
					'{address_1}',
					'{address_2}',
					'{city}',
					'{postcode}',
					'{zone}',
					'{zone_code}',
					'{country}'
				);

				$replace = array(
					'fullname' => $order_info['shipping_fullname'],
					'company'   => $order_info['shipping_company'],
					'address_1' => $order_info['shipping_address_1'],
					'address_2' => $order_info['shipping_address_2'],
					'city'      => $order_info['shipping_city'],
					'postcode'  => $order_info['shipping_postcode'],
					'zone'      => $order_info['shipping_zone'],
					'zone_code' => $order_info['shipping_zone_code'],
					'country'   => $order_info['shipping_country']
				);

				// $data['shipping_address'] = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));
				$data['shipping_address'] = $order_info['shipping_address'];

				$data['shipping_method'] = $order_info['shipping_method'];

				$data['expected_delivery_date'] ="2016-03-29";

				$data['products'] = array();

				$products = $this->model_account_order->getOrderProducts($order_id);

                $this->load->model('catalog/product');

				foreach ($products as $product) {
					$option_data = array();

					$options = $this->model_account_order->getOrderOptions($order_id, $product['order_product_id']);

					foreach ($options as $option) {
						if ($option['type'] != 'file') {
							$value = $option['value'];
						} else {
							$value = utf8_substr($option['value'], 0, utf8_strrpos($option['value'], '.'));
						}

						$option_data[] = array(
							'name'  => $option['name'],
							'value' => (utf8_strlen($value) > 20 ? utf8_substr($value, 0, 20) . '..' : $value)
						);					
					}
                    $product_info = $this->model_catalog_product->getProduct($product['product_id']);

                    if ($product_info) {
                        $order_product_id = $product['order_product_id'];
                    } else {
                        $order_product_id = '';
                    }

					$data['products'][] = array(
						'name'     => $product['name'],
						'model'    => $product['model'],
						'option'   => $option_data,
						'quantity' => $product['quantity'],
						'sku'	   => $product_info['sku'],
            			'order_product_id'  => $order_product_id,
            			'product_id'  => $product['product_id'],
						'price'    => $this->currency->format($product['price'] + ($this->config->get('config_tax') ? $product['tax'] : 0), $order_info['currency_code'], $order_info['currency_value']),
						'total'    => $this->currency->format($product['total'] + ($this->config->get('config_tax') ? ($product['tax'] * $product['quantity']) : 0), $order_info['currency_code'], $order_info['currency_value']),
						'return'   => $this->url->link('account/return/insert', 'order_id=' . $order_info['order_id'] . '&product_id=' . $product['product_id'], 'SSL'),
						'image'	   => $this->model_catalog_product->getProductImageByProductId($product['product_id']),
						'can_comment'=> empty($product['review_id'])?true:false,
					);
				}

				// Voucher
				$data['vouchers'] = array();

				$vouchers = $this->model_account_order->getOrderVouchers($order_id);

				foreach ($vouchers as $voucher) {
					$data['vouchers'][] = array(
						'description' => $voucher['description'],
						'amount'      => $this->currency->format($voucher['amount'], $order_info['currency_code'], $order_info['currency_value'])
					);
				}

				$data['totals'] = $this->model_account_order->getOrderTotals($order_id);

				$data['comment'] = nl2br($order_info['comment']);

				$data['histories'] = array();

				$results = $this->model_account_order->getOrderHistories($order_id);

				foreach ($results as $result) {
					$data['histories'][] = array(
						'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added'])),
						'status'     => $result['status'],
						'comment'    => nl2br($result['comment'])
					);
				}

				$json["data"] = $data;
			}else {
					$json['success']     = false;
					$json['error']['warning']     = "这个订单不存在";
			}

			

			if ($this->debugIt) {
				echo '<pre>';
				print_r($json);
				echo '</pre>';
			} else {
				$this->response->setOutput(json_encode($json));
			}
        } else {
            $this->response->setOutput(json_encode($json));
        }
    }

	public function reorder($order_id,$order_product_id) {

		$json = array('success' => true);
		
		if (!$this->customer->isLogged()) {
			$json["error"]["warning"] = "用户没有登陆";
			$json["success"] = false;
		}

		$this->language->load('account/order');

		$this->load->model('account/order');

		
		if($json["success"]){
			/*reorder*/
			if (isset($order_id)) {

				$order_info = $this->model_account_order->getOrder($order_id);

				if ($order_info) {

					$order_product_info = $this->model_account_order->getOrderProduct($order_id, $order_product_id);

					if ($order_product_info) {
						$this->load->model('catalog/product');

						$product_info = $this->model_catalog_product->getProduct($order_product_info['product_id']);

						if ($product_info) {
							$option_data = array();

							$order_options = $this->model_account_order->getOrderOptions($order_product_info['order_id'], $order_product_id);

							foreach ($order_options as $order_option) {
								if ($order_option['type'] == 'select' || $order_option['type'] == 'radio' || $order_option['type'] == 'image') {
									$option_data[$order_option['product_option_id']] = $order_option['product_option_value_id'];
								} elseif ($order_option['type'] == 'checkbox') {
									$option_data[$order_option['product_option_id']][] = $order_option['product_option_value_id'];
								} elseif ($order_option['type'] == 'text' || $order_option['type'] == 'textarea' || $order_option['type'] == 'date' || $order_option['type'] == 'datetime' || $order_option['type'] == 'time') {
									$option_data[$order_option['product_option_id']] = $order_option['value'];
								} elseif ($order_option['type'] == 'file') {
									$option_data[$order_option['product_option_id']] = $this->encryption->encrypt($order_option['value']);
								}
							}

							$this->cart->add($order_product_info['product_id'], $order_product_info['quantity'], $option_data);

							$this->session->data['success'] = sprintf($this->language->get('text_success'), $this->url->link('product/product', 'product_id=' . $product_info['product_id']), $product_info['name'], $this->url->link('checkout/cart'));

							unset($this->session->data['shipping_method']);
							unset($this->session->data['shipping_methods']);
							unset($this->session->data['payment_method']);
							unset($this->session->data['payment_methods']);
						} else {
							$this->session->data['error'] = sprintf($this->language->get('error_reorder'), $order_product_info['name']);
							$json['success']     = false;
						}
					} else {
						$json['success']     = false;
						$json['error']['warning']       = "指定的项目不存在";
					}
				}else {
					$json['success']     = false;
					$json['error']['warning'] = "指定的订单不存在";
				}
			}else {
					$json['success']     = false;
					$json['error']['warning'] = "指定的订单不存在";
			}		
		}

        if($json['success']){
            $json['error']['warning']      = "你需要添加产品到购物车";
        }

		if ($this->debugIt) {
			echo '<pre>';
			print_r($json);
			echo '</pre>';
		} else {
			$this->response->setOutput(json_encode($json));
		}					
	}


	/*
	* ORDERS FUNCTIONS
	*/	
	public function orders() {

		$this->checkPlugin();
		

		if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
			//get order details
			if (isset($this->request->get['id']) && ctype_digit($this->request->get['id'])) {
				$this->getOrder($this->request->get['id']);
			}else {
				//get order list
				$this->listOrders();
			}
		}else if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){
			//reorder
			if (isset($this->request->get['id']) && ctype_digit($this->request->get['id'])) {
                if (isset($this->request->get['order_product_id'])) {
                    $order_product_id = $this->request->get['order_product_id'];
                } else {
                    $order_product_id = 0;
                }

				$this->reorder($this->request->get['id'], $order_product_id);
			}else {
				$this->response->setOutput(json_encode(array('success' => false)));
			}   

		}

  }

  public function updateSalesInfo(){
      $this->load->model('catalog/product');
      $query = $this->model_catalog_product->everydaySales();
      return $query;
  }

  public function getLuckydraw() {
  	$json = array('success'=>false);
  	if (isset($this->request->get['id']) && ctype_digit($this->request->get['id'])) {
			$order_id = $this->request->get['id'];
		}
		$this->language->load('account/order');
		$this->load->model('account/order');
		$order_info = $this->model_account_order->getOrder($order_id);
		if($order_info) {
			$luckydraw = $this->model_account_order->getLuckydraw($order_info);	
			if($luckydraw) {
				$json['luckydraw'] = $luckydraw;
				$json['success'] = true;
			}
		}
		if(!$json['success']) {
			$json['error']['warning'] = "未找到幸运抽奖";
		}
		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	public function tryLuck() {
  		$json = array('success'=>false);
  		if (isset($this->request->get['id']) && ctype_digit($this->request->get['id'])) {
			$order_id = $this->request->get['id'];
		}
		$this->language->load('account/order');
		$this->load->model('account/order');
		$order_info = $this->model_account_order->getOrder($order_id);
		if($order_info) {
			$luckydraw = $this->model_account_order->getLuckydraw($order_info);	
			if($luckydraw && $luckydraw['left_times']>0) {
				$price = $this->model_account_order->drawPrice($order_id,$order_info['total'],$luckydraw['luckydraw_id'],$luckydraw['left_times']);
				$luckydraw = $this->model_account_order->getLuckydraw($order_info);	
				$luckydraw['item']=$price['item'];
  			$json['luckydraw'] = $luckydraw;
				$json['success'] = true;
			}
		}
		if(!$json['success']) {
			$json['error']['warning'] = "未找到幸运抽奖";
		}
		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}
}